#include "Terrain.h"
#include <stdio.h>
#include <malloc.h>
#include <assert.h>
#include <string.h>

void terInit(Terrain * pTer,int id){ /*initialisation d'un terrain, appelée avec un Id */
                                    /* dans le cas ou on ferai plusieurs terrains*/
	FILE * f;

	int x,y;
	char tName[50];

	sprintf(tName,"data/Database/Terrain%d.dat",id);
	f = fopen(tName,"r");
	if(f==NULL){
	sprintf(tName,"../data/Database/Terrain%d.dat",id);
	f = fopen(tName,"r");
	}

	assert(f!=NULL);

	pTer->name=(char *)malloc(20*sizeof(char));

	fscanf(f,"#name = %s\n",pTer->name);
	fscanf(f,"#dimx = %d\n",&(pTer->dimx));
	fscanf(f,"#dimy = %d\n",&(pTer->dimy));

	pTer->tab = (Case **) malloc(pTer->dimy*sizeof(Case *));

	for(y=0;y<pTer->dimy;y++){
			pTer->tab[y]=(Case *)malloc(pTer->dimx*sizeof(Case));
	       }

	for(y=0;y<pTer->dimy;y++){
		for(x=0;x<pTer->dimx;x++){
			fscanf(f,"%c",&(pTer->tab[y][x].ch));
			if(pTer->tab[y][x].ch == '#'){ pTer->tab[y][x].stat = OCCUPIED; }
			else{ pTer->tab[y][x].stat = FREE; }
		}
	fscanf(f,"\n");
	}

	fclose(f);
}


void terFree(Terrain * pTer){

	int y;
	for(y=0;y<pTer->dimy;y++){
			free(pTer->tab[y]);
			pTer->tab[y] = NULL;
	       }

	free(pTer->tab);
	pTer->tab = NULL;

	free(pTer->name);
	pTer->name = NULL;


}


char terGetXY(const Terrain * pTer, const int x,const int y){

	assert(x < pTer->dimx && y < pTer->dimy);

	return pTer->tab[y][x].ch;

}

int terTestPosition(const Terrain * pTer, const int x, const int y){

	assert(x < pTer->dimx && y < pTer->dimy);

	if(pTer->tab[y][x].stat == FREE) return 1;

	return 0;
}

int getDimx(const Terrain * pTer){
	return pTer->dimx;
}

int getDimy(const Terrain * pTer){
	return pTer->dimy;
}

void terModif(Terrain * pTer, int x, int y, int stat){ /*fonction qui modifie le champs "stat" de la structure case*/

	assert(x < pTer->dimx && y < pTer->dimy);

	assert(stat == 1 || stat == 0);

	if(stat == 1){
		pTer->tab[y][x].stat = OCCUPIED;
	}else{
		pTer->tab[y][x].stat = FREE;
	}


}

char * getTerName(const Terrain * pTerrain){
return pTerrain->name;
}

void terrTestRegression(){

	Terrain pTer;
	printf("****** TEST TERRAIN START ************ \n");

	terInit(&pTer,1);

	terModif(&pTer,10,10,1);
	terModif(&pTer,10,10,0);

	if(terTestPosition(&pTer,10,10)){
		printf("Module travaille correctement.....\n");
	}else{
		printf("Attention! Module erreur......\n");
	}

	terFree(&pTer);
	printf("****** TEST TERRAIN END ************** \n");

}


